package org.lemon.transport.coap.server.service;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.californium.core.CoapServer;
import org.eclipse.californium.core.config.CoapConfig;
import org.eclipse.californium.core.network.CoapEndpoint;
import org.eclipse.californium.core.server.resources.Resource;
import org.eclipse.californium.elements.config.Configuration;
import org.eclipse.californium.scandium.DTLSConnector;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.lemon.transport.coap.server.session.CoapDtlsSessionInfo;
import org.lemon.transport.coap.server.config.CoapDtlsSettings;
import org.lemon.transport.context.utils.DefaultThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static org.eclipse.californium.core.config.CoapConfig.DEFAULT_BLOCKWISE_STATUS_LIFETIME_IN_SECONDS;

@Slf4j
@Service
public class CoapService {

    @Getter
    @Value("${transport.coap.bind_address}")
    private String host;

    @Getter
    @Value("${transport.coap.bind_port}")
    private Integer port;

    @Getter
    @Value("${transport.coap.timeout}")
    private Long timeout;

    @Getter
    @Value("${transport.coap.psm_activity_timer:10000}")
    private long psmActivityTimer;

    @Getter
    @Value("${transport.coap.paging_transmission_window:10000}")
    private long pagingTransmissionWindow;

    @Getter
    @Autowired(required = false)
    private CoapDtlsSettings dtlsSettings;

    private CoapServer server;

    @Getter
    private CoapDtlsCertificateVerifier dtlsCertificateVerifier;

    @Getter
    private ScheduledExecutorService dtlsSessionsExecutor;

    @PostConstruct
    public void init() throws UnknownHostException {
        this.server = createCoapServer();
    }

    @PreDestroy
    public void shutdown() {

        if (dtlsSessionsExecutor != null) {
            dtlsSessionsExecutor.shutdown();
        }
        log.info("Stopping Coap server!");
        server.destroy();
        ;
        log.info("Coap server stopped!");
    }

    public CoapServer getCoapServer() throws UnknownHostException {

        if (server != null) {
            return server;
        }
        return createCoapServer();
    }

    public ConcurrentMap<InetSocketAddress, CoapDtlsSessionInfo> getDtlsSessionsMap() {
        return dtlsCertificateVerifier != null ? dtlsCertificateVerifier.getCoapDtlsSessionsMap() : null;
    }

    private CoapServer createCoapServer() throws UnknownHostException {

        Configuration networkConfig = new Configuration();
        networkConfig.set(CoapConfig.BLOCKWISE_STRICT_BLOCK2_OPTION, true);
        networkConfig.set(CoapConfig.BLOCKWISE_ENTITY_TOO_LARGE_AUTO_FAILOVER, true);
        networkConfig.set(CoapConfig.BLOCKWISE_STATUS_LIFETIME, DEFAULT_BLOCKWISE_STATUS_LIFETIME_IN_SECONDS, TimeUnit.SECONDS);
        networkConfig.set(CoapConfig.MAX_RESOURCE_BODY_SIZE, 256 * 1024 * 1024);
        networkConfig.set(CoapConfig.RESPONSE_MATCHING, CoapConfig.MatcherMode.RELAXED);
        networkConfig.set(CoapConfig.PREFERRED_BLOCK_SIZE, 1024);
        networkConfig.set(CoapConfig.MAX_MESSAGE_SIZE, 1024);
        networkConfig.set(CoapConfig.MAX_RETRANSMIT, 4);
        networkConfig.set(CoapConfig.COAP_PORT, this.port);
        server = new CoapServer(networkConfig);

        CoapEndpoint.Builder noSecCoapEndpointBuilder = new CoapEndpoint.Builder();
        InetAddress addr = InetAddress.getByName(this.host);
        InetSocketAddress sockAddr = new InetSocketAddress(addr, this.port);
        noSecCoapEndpointBuilder.setInetSocketAddress(sockAddr);

        noSecCoapEndpointBuilder.setConfiguration(networkConfig);
        CoapEndpoint noSecCoapEndpoint = noSecCoapEndpointBuilder.build();
        server.addEndpoint(noSecCoapEndpoint);
        if (isDtlsEnabled()) {

            CoapEndpoint.Builder dtlsCoapEndpointBuilder = new CoapEndpoint.Builder();
            DtlsConnectorConfig dtlsConnectorConfig = dtlsSettings.dtlsConnectorConfig(networkConfig);
            networkConfig.set(CoapConfig.COAP_SECURE_PORT, dtlsConnectorConfig.getAddress().getPort());
            dtlsCoapEndpointBuilder.setConfiguration(networkConfig);
            DTLSConnector connector = new DTLSConnector(dtlsConnectorConfig);
            dtlsCoapEndpointBuilder.setConnector(connector);
            CoapEndpoint dtlsCoapEndpoint = dtlsCoapEndpointBuilder.build();
            server.addEndpoint(dtlsCoapEndpoint);
            dtlsCertificateVerifier = (CoapDtlsCertificateVerifier) dtlsConnectorConfig.getAdvancedCertificateVerifier();
            dtlsSessionsExecutor = Executors.newSingleThreadScheduledExecutor(DefaultThreadFactory.forName(getClass().getSimpleName()));
            dtlsSessionsExecutor.scheduleAtFixedRate(this::evictTimeoutSessions, new Random().nextInt((int) dtlsSettings.getDtlsSessionReportTimeout()), dtlsSettings.getDtlsSessionReportTimeout(), TimeUnit.MILLISECONDS);
        }

        Resource root = server.getRoot();
        CoapServerMessageDeliverer messageDeliverer = new CoapServerMessageDeliverer(root);
        server.setMessageDeliverer(messageDeliverer);
        server.start();
        log.info("CoAP server started on port(s): {}", port);
        return server;
    }

    private boolean isDtlsEnabled() {
        return this.dtlsSettings != null && this.dtlsSettings.isEnabled();
    }

    private void evictTimeoutSessions() {
        dtlsCertificateVerifier.getCoapDtlsSessionInMemoryStorage().evictTimeoutSessions();
    }
}
